package com.ld.zxw.core;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.NoLockFactory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.IPlugin;
import com.ld.zxw.config.Config;
import com.ld.zxw.config.LuceneDataSource;
import redis.clients.jedis.Jedis;

/**
 * 启动 插件  jfinal 最佳  兼容过滤器启动
 * @author zxw
 *
 */
public class LucenePlugin implements IPlugin{

	private Logger log = Logger.getLogger(LucenePlugin.class);

	public List<JSONObject> list;


	/**
	 * 不使用动态词库
	 */
	public LucenePlugin() {
		list = new ArrayList<>();
	}

	/**
	 * 加载redis  使用动态词库
	 * @param redisHost 地址：例 127.0.0.1 必填
	 * @param redisPort 端口号： 例 6379  必填
	 * @param redisPwd  密码 ： 不必填
	 */
	public LucenePlugin(String redisHost,int redisPort,String redisPwd) {
		list = new ArrayList<>();
		LuceneDataSource.jedis = new Jedis(redisHost,redisPort == 0 ? 6379 : redisPort);
		if(StringUtils.isNotBlank(redisPwd)){
			LuceneDataSource.jedis.auth(redisPwd);
		}
		LuceneDataSource.DynamicDictionary = true;
	}

	/**
	 * 添加数据源
	 * @param <T>
	 * @param config
	 * @param sourceName
	 * @param analyzer
	 * @param sourceKey
	 * @param class1 
	 */
	public <T> void putDataSource(Config config,String sourceKey) {
		JSONObject object = new JSONObject();
		object.put("config", config);
		object.put("sourceKey", sourceKey);
		list.add(object);
	}


	@Override
	public boolean start() {
		LuceneDataSource dataSource = new LuceneDataSource();
		try {
			int size = list.size();
			for (int i = 0; i < size; i++) {
				JSONObject object = list.get(i);
				Config config = object.getObject("config",Config.class);
				String sourceKey = object.getString("sourceKey");
				if(config.getAnalyzer() == null) {
					config.setAnalyzer(new PerFieldAnalyzerWrapper(new IKAnalyzer(false,config)));
				}
				Config cof = new Config();
				cof.setAnalyzer(config.getAnalyzer());
				cof.setLucenePath(config.getLucenePath());
				cof.setHighlight(config.isHighlight());
				cof.setHighlightConf(config.getHighlightConf());
				cof.setBoostField(config.getBoostField());
				cof.setParticipleField(config.getParticipleField());
				cof.setHighlightFields(config.getHighlightFields());
				setPath(cof, sourceKey);
				//预定义读写对象
				setIndexWriter(cof);
				setIndexSearcher(cof);
				dataSource.addDataSource(cof, sourceKey);
			}
			LogKit.info("LucenePlus 加载完毕!");
			return true;
		} catch (Exception e) {
			log.error("LucenePlugin.start()", e);
			return false;
		}
	}

	/**
	 * 设置搜索对象
	 * @param config
	 */
	public void setIndexSearcher(Config config) {
		DirectoryReader open = null;
		try {
			open = DirectoryReader.open(config.getIndexWriter());
		} catch (IOException e) {
			e.printStackTrace();
		}
		IndexSearcher searcher = new IndexSearcher(open);
		config.setIndexSearcher(searcher);
	}

	/**
	 * 设置写入对象
	 * @param config
	 */
	public void setIndexWriter(Config config) {
		IndexWriter indexWriter = null;
		try {
			indexWriter = new IndexWriter(FSDirectory.open(config.getPath(), NoLockFactory.INSTANCE),
					new IndexWriterConfig(config.getAnalyzer()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		config.setIndexWriter(indexWriter);
	}

	/**
	 * 设置目录
	 * @param conf
	 * @param sourceKey
	 */
	public void setPath(Config conf,String sourceKey) {
		try {
			String lucene_core = conf.getLucenePath()+sourceKey+"/data";
			//不存在 创建
			File file = new File(lucene_core);
			if(!file.isDirectory()) {
				file.mkdirs();
			}
			Path path = Paths.get(lucene_core);
			conf.setPath(path);
		} catch (Exception e) {
			log.error("LucenePlugin.setPath()", e);
		}
	}

	@Override
	public boolean stop() {
		LuceneDataSource.jedis.close();
		return true;
	}
	public static void main(String[] args) {
		File file = new File("d:/");
		System.out.println(file.isDirectory());
	}
}
